package com.youzan.cloud.common.aspect;

import com.youzan.cloud.common.annotation.Oauth;
import com.youzan.cloud.common.constant.TokenConstant;
import com.youzan.cloud.common.exception.AuthenticationFailExcetion;
import com.youzan.cloud.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @author tangsen233
 * @version 1.0
 * @description: oauth验签
 * @date 2021/12/15 12:03
 */
@Component
@Aspect
@Slf4j
public class OauthRequiredAspect {

    @Resource
    RedisUtil redisUtil;

    @Before("@annotation(requestRequired)")
    public void check(Oauth requestRequired) {
        //获取request
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String access_token = request.getHeader("access_token");
        String app_id = request.getHeader("app_id");
        if (StringUtils.isBlank(access_token)) {
            throw new AuthenticationFailExcetion("access_token为空");
        }
        if (StringUtils.isBlank(app_id)) {
            throw new AuthenticationFailExcetion("app_id为空");
        }
        String token = redisUtil.get(TokenConstant.TOKEN_PREFIX + app_id);
        if (StringUtils.isBlank(token)) {
            throw new AuthenticationFailExcetion("对应app_id的access_token已过期,请重新获取");
        }
        if (!Objects.equals(access_token, token)) {
            throw new AuthenticationFailExcetion("access_token不一致");
        }
    }

}